from django.shortcuts import render
from rest_framework import status
from rest_framework.generics import GenericAPIView
from django_redis import get_redis_connection
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from goods.models import SKU
from orders.models import OrderGoods
from orders.serializers import OrderPlaceSerializer, OrderCommitSerializer, OrderCommentSerializer, \
    OrderCommentGetSerializer
from decimal import Decimal
from rest_framework.generics import CreateAPIView
from rest_framework.generics import GenericAPIView
from rest_framework.generics import ListAPIView
#获取订单视图
class OrderPlaceView(GenericAPIView):
    serializer_class = OrderPlaceSerializer
    permission_classes = [IsAuthenticated]

    def get(self, request):
        # 1,获取redis中需要结算的商品
        user = request.user
        redis_conn = get_redis_connection("cart")
        cart_dict = redis_conn.hgetall("cart_%s" % user.id)
        cart_selected_list = redis_conn.smembers("cart_selected_%s"%user.id)

        # 2,拼接数据
        sku_list = []
        for sku_id  in cart_selected_list:
            sku = SKU.objects.get(id=sku_id)
            sku.count = int(cart_dict[sku_id])
            sku_list.append(sku)

        # 3,获取序列化器
        serializer = self.get_serializer(instance=sku_list,many=True)

        # 4,返回响应
        contenxt = {
            "skus":serializer.data,
            "freight":Decimal(10.0)
        }
        return Response(contenxt)
#订单提交视图
class OrderCommitView(CreateAPIView):
    serializer_class = OrderCommitSerializer
    permission_classes = [IsAuthenticated]
#查看和提交评价视图
class OrderCommentView(GenericAPIView):
    serializer_class = OrderCommentSerializer
    permission_classes = [IsAuthenticated]
    def get(self, request, order_id):
        try:
            ordergoods = OrderGoods.objects.filter(order=order_id,is_commented=False)
        except Exception as e:
            return Response(status=status.HTTP_404_NOT_FOUND)
        #获取序列化器 校验
        serializer = self.get_serializer(instance=ordergoods,many=True)
        #返回响应
        return Response(serializer.data)

#提交评价和查看评价视图
    def post(self,request,order_id):
        #1.获取参数
        dict_data = request.data
        #2.获取序列化器 校验
        serializer = self.get_serializer(data=dict_data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        #3.返回响应
        return Response(serializer.data)

#商品详情页面查看评价视图
class OrderCommentGetView(ListAPIView):
    serializer_class = OrderCommentGetSerializer
    def get_queryset(self):
        return OrderGoods.objects.filter(sku_id=self.kwargs.get('sku_id'), is_commented=True)
